import { history } from 'umi';
import { message } from 'antd';
import _ from 'lodash';
import { login } from '@/services/global';

const namespace = 'global';

export default {
  namespace,
  state: {
    user: null,
  },
  effects: {
    *login({ payload }, { call, put }) {
      const res = yield call(login, { ...payload });
      if (res.success) {
        const { user, token } = res.data;
        yield put({
          type: 'save',
          payload: { user },
        });
        window.sessionStorage.setItem('Authorization', token);
        window.sessionStorage.setItem('user', JSON.stringify(user));
        message.success('登录成功！');
        history.replace('/main/home');
      } else {
        message.warn(res.msg);
      }
    },
    // 根据Token获取当前用户信息
    *current(_, { call, put }) {
      const user = JSON.parse(window.sessionStorage.getItem('user'));
      if (user) {
        yield put({
          type: 'save',
          payload: { user },
        });
      } else {
        history.replace('/login');
      }
    },
    *logout(_, { call }) {
      // const res = yield call(logout);
      // if (res.success) {
      window.sessionStorage.removeItem('Authorization');
      window.sessionStorage.removeItem('user');
      history.replace({
        pathname: '/login',
        search: `timestamp=${new Date().getTime()}`,
      });
      // }
    },
  },
  reducers: {
    // 同步
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
  subscriptions: {
    // 监听路由变化，鼠标，键盘变化，服务器连接变化等
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        console.log(pathname);
      });
    },
  },
};
